package com.zhentao.task;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.domain.UseBattery;
import com.zhentao.service.UseBatteryService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@EnableScheduling
public class UseBatteryTask {
    @Autowired
    private UseBatteryService useBatteryService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //每20分钟执行一次
    @Scheduled(cron = "0 0/20 * * * ? ")
    public void useBatteryTask(){
        List<UseBattery> list = useBatteryService.list(Wrappers.<UseBattery>lambdaQuery().orderByDesc(UseBattery::getCreateTime));
        stringRedisTemplate.opsForValue().set("useBattery", JSON.toJSONString(list));
    }
    @PostConstruct
    public void init(){
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey("useBattery"))){
            List<UseBattery> list = useBatteryService.list(Wrappers.<UseBattery>lambdaQuery().orderByDesc(UseBattery::getCreateTime));
            stringRedisTemplate.opsForValue().set("useBattery", JSON.toJSONString(list));
        }

    }
}
